use crate::core::{
    message::{AppEvent, GitResult},
    state::AppState,
};
use anyhow::Result;
use crossterm::event::{self, Event};
use crossterm::event::{KeyCode, KeyEventKind};
use log::debug;
use std::time::Duration;
use tokio::{sync::mpsc, time};

pub async fn handle_branch_key(app_state: &AppState, key: KeyCode) -> Result<()> {
    debug!("handle_branch_key: {:?}", key);
    match key {
        KeyCode::Enter => {
            // 查看是否需要切换分支，或者切换到提交列表视图
            let (branch, commits_loaded) = {
                let app = app_state.app_data.lock().await;
                (
                    app.branches[app.selected_index].clone(),
                    !app.commits.is_empty(),
                )
            }; // 锁在这里被释放

            // 如果已经加载了提交，切换到提交列表视图
            if commits_loaded {
                // 切换到提交列表视图
                app_state
                    .update_app(|app| {
                        app.ui_state = crate::ui::app::AppState::CommitList;
                        app.selected_index = 0; // 重置选择索引，从第一个提交开始
                        app.current_diff = None; // 清空上一个 diff
                        app.set_notification(
                            format!("Viewing commits for branch '{}'", branch),
                            2000,
                        );
                    })
                    .await;

                // 触发加载第一个提交的 diff
                let first_commit_id = {
                    let app = app_state.app_data.lock().await;
                    if !app.commits.is_empty() {
                        Some(app.commits[0].id.clone())
                    } else {
                        None
                    }
                };

                if let Some(id) = first_commit_id {
                    let _ = app_state.event_sender.send(AppEvent::LoadCommitDiff(id)).await;
                }
                return Ok(());
            }
        }
        KeyCode::Char('m') => {
            // 进入合并模式
            let branch = app_state
                .update_app(|app| {
                    if !app.branches.is_empty() && app.selected_index < app.branches.len() {
                        Some(app.branches[app.selected_index].clone())
                    } else {
                        None
                    }
                })
                .await;

            if let Some(branch_name) = branch {
                app_state
                    .update_app(|app| {
                        app.set_notification(
                            format!("Loading commits for branch '{}'", branch_name),
                            1000,
                        );
                    })
                    .await;

                // 发送事件而不是直接调用方法
                let _ = app_state
                    .event_sender
                    .send(AppEvent::ShowMergeList(branch_name))
                    .await;
            }
        }
        KeyCode::Char('c') => {
            let (branch, current_branch, has_changes) = {
                let app = app_state.app_data.lock().await;
                (
                    app.branches[app.selected_index].clone(),
                    app.current_branch.clone(),
                    app.has_changes,
                )
            }; // 锁在这里被释放

            // 如果选中的分支与当前分支相同，不执行任何操作
            if let Some(current) = current_branch {
                debug!("branch: {}, current branch: {}", branch, current);
                if current == branch {
                    app_state
                        .update_app(|app| {
                            app.set_notification(format!("Already on branch '{}'", branch), 1500);
                        })
                        .await;
                    return Ok(());
                }
            }

            // 触发显示分支切换确认对话框事件
            // 真实的 has_changes 值将在处理 GitResult::RepoStatus 时设置
            let _ = app_state
                .event_sender
                .send(AppEvent::ShowBranchSwitchDialog {
                    branch: branch.clone(),
                    has_changes, // 暂时置为 false，实际值会在处理仓库状态时设置
                })
                .await;
        }
        KeyCode::Up | KeyCode::Char('k') => {
            // 向上导航
            let branch = app_state
                .update_app(|app| {
                    if !app.branches.is_empty() {
                        app.selected_index = if app.selected_index > 0 {
                            app.selected_index - 1
                        } else {
                            app.branches.len() - 1
                        };
                    }
                    // 返回当前选择的分支名称
                    if !app.branches.is_empty() && app.selected_index < app.branches.len() {
                        Some(app.branches[app.selected_index].clone())
                    } else {
                        None
                    }
                })
                .await;

            // 如果有选择的分支，发送BranchSelected事件
            if let Some(branch_name) = branch {
                app_state
                    .update_app(|app| {
                        app.set_notification(
                            format!("Loading commits for branch '{}'", branch_name),
                            1000,
                        );
                    })
                    .await;

                // 发送事件而不是直接调用方法
                let _ = app_state
                    .event_sender
                    .send(AppEvent::BranchSelected(branch_name))
                    .await;
            }
        }
        KeyCode::Down | KeyCode::Char('j') => {
            // 向下导航
            let branch = app_state
                .update_app(|app| {
                    if !app.branches.is_empty() {
                        app.selected_index = (app.selected_index + 1) % app.branches.len();
                    }
                    // 返回当前选择的分支名称
                    if !app.branches.is_empty() && app.selected_index < app.branches.len() {
                        Some(app.branches[app.selected_index].clone())
                    } else {
                        None
                    }
                })
                .await;

            // 如果有选择的分支，发送BranchSelected事件
            if let Some(branch_name) = branch {
                app_state
                    .update_app(|app| {
                        app.set_notification(
                            format!("Loading commits for branch '{}'", branch_name),
                            1000,
                        );
                    })
                    .await;

                // 发送事件而不是直接调用方法
                let _ = app_state
                    .event_sender
                    .send(AppEvent::BranchSelected(branch_name))
                    .await;
            }
        }
        // 可以添加Tab键在左右面板之间切换焦点
        _ => {}
    }

    Ok(())
}

pub async fn handle_merge_key(app_state: &AppState, key: KeyCode) -> Result<()> {
    match key {
        KeyCode::Up | KeyCode::Char('k') => {
            // 向上导航
            app_state
                .update_app(|app| {
                    if !app.commits.is_empty() {
                        if !app.commits.is_empty() {
                            app.selected_index = if app.selected_index > 0 {
                                app.selected_index - 1
                            } else {
                                app.commits.len() - 1
                            };
                            // 清空旧的diff并准备加载新的
                            app.current_diff = None;
                        }
                    }
                })
                .await;

            // 获取新选中的commit_id并发送加载事件
            let commit_id_to_load = {
                let app = app_state.app_data.lock().await;
                if !app.commits.is_empty() && app.selected_index < app.commits.len() {
                    Some(app.commits[app.selected_index].id.clone())
                } else {
                    None
                }
            };
            if let Some(id) = commit_id_to_load {
                let _ = app_state.event_sender.send(AppEvent::LoadCommitDiff(id)).await;
            }
        }
        KeyCode::Down | KeyCode::Char('j') => {
            // 向下导航
            app_state
                .update_app(|app| {
                    if !app.commits.is_empty() {
                        app.selected_index = (app.selected_index + 1) % app.commits.len();
                        // 清空旧的diff并准备加载新的
                        app.current_diff = None;
                    }
                })
                .await;

            // 获取新选中的commit_id并发送加载事件
            let commit_id_to_load = {
                let app = app_state.app_data.lock().await;
                if !app.commits.is_empty() && app.selected_index < app.commits.len() {
                    Some(app.commits[app.selected_index].id.clone())
                } else {
                    None
                }
            };
            if let Some(id) = commit_id_to_load {
                let _ = app_state.event_sender.send(AppEvent::LoadCommitDiff(id)).await;
            }
        }
        KeyCode::Char(' ') => {
            // 切换当前提交的选中状态
            app_state
                .update_app(|app| {
                    app.toggle_commit_selection();
                })
                .await;
        }
        KeyCode::Char('a') => {
            // 切换全选/取消全选状态
            app_state
                .update_app(|app| {
                    let commits_count = app.commits.len();
                    let selected_count = app.selected_commits.len();

                    // 如果当前所有提交都已选中，则清除全部选择
                    if selected_count == commits_count && !app.commits.is_empty() {
                        app.clear_commit_selections();
                        app.set_notification("Cleared all selections".to_string(), 2000);
                    } else {
                        // 否则全选所有提交
                        app.clear_commit_selections();
                        for i in 0..commits_count {
                            app.selected_commits.push(i);
                        }
                        app.set_notification(
                            format!("Selected all {} commits", commits_count),
                            2000,
                        );
                    }
                })
                .await;
        }
        KeyCode::Enter => {
            // 确认合并
            let (branch, commit_ids) = app_state
                .update_app(|app| {
                    let branch = app.merge_source_branch.clone();
                    let commit_ids = app.get_selected_commit_ids();
                    // 清除选中状态和合并源分支
                    app.clear_commit_selections();
                    app.merge_source_branch = None;
                    // 返回到分支列表
                    app.ui_state = crate::ui::app::AppState::BranchList;
                    (branch, commit_ids)
                })
                .await;

            if let Some(branch_name) = branch {
                if !commit_ids.is_empty() {
                    // 发送合并事件
                    let _ = app_state
                        .event_sender
                        .send(AppEvent::MergeSelected {
                            branch: branch_name,
                            commit_ids,
                        })
                        .await;
                } else {
                    // 无选中提交，显示通知
                    app_state
                        .update_app(|app| {
                            app.set_notification("No commits selected for merge".to_string(), 2000);
                        })
                        .await;
                }
            }
        }
        KeyCode::Esc => {
            // 取消合并，返回分支列表
            app_state
                .update_app(|app| {
                    app.ui_state = crate::ui::app::AppState::BranchList;
                    app.clear_commit_selections();
                    app.merge_source_branch = None;
                    app.set_notification("Merge cancelled".to_string(), 1500);
                })
                .await;

            // 发送取消合并事件
            let _ = app_state.event_sender.send(AppEvent::MergeCancelled).await;
        }
        _ => {}
    }

    Ok(())
}

pub async fn handle_commit_key(app_state: &AppState, key: KeyCode) -> Result<()> {
    debug!("handle_commit_key: {:?}", key);
    match key {
        KeyCode::Up | KeyCode::Char('k') => {
            // 向上导航
            app_state
                .update_app(|app| {
                    if !app.commits.is_empty() {
                        app.selected_index = if app.selected_index > 0 {
                            app.selected_index - 1
                        } else {
                            app.commits.len() - 1
                        };
                        // 清空旧的diff并准备加载新的
                        app.current_diff = None;
                    }
                })
                .await;

            // 获取新选中的commit_id并发送加载事件
            let commit_id_to_load = {
                let app = app_state.app_data.lock().await;
                if !app.commits.is_empty() && app.selected_index < app.commits.len() {
                    Some(app.commits[app.selected_index].id.clone())
                } else {
                    None
                }
            };
            if let Some(id) = commit_id_to_load {
                let _ = app_state.event_sender.send(AppEvent::LoadCommitDiff(id)).await;
            }
        }
        KeyCode::Down | KeyCode::Char('j') => {
            // 向下导航
            app_state
                .update_app(|app| {
                    if !app.commits.is_empty() {
                        app.selected_index = (app.selected_index + 1) % app.commits.len();
                        // 清空旧的diff并准备加载新的
                        app.current_diff = None;
                    }
                })
                .await;

            // 获取新选中的commit_id并发送加载事件
            let commit_id_to_load = {
                let app = app_state.app_data.lock().await;
                if !app.commits.is_empty() && app.selected_index < app.commits.len() {
                    Some(app.commits[app.selected_index].id.clone())
                } else {
                    None
                }
            };
            if let Some(id) = commit_id_to_load {
                let _ = app_state.event_sender.send(AppEvent::LoadCommitDiff(id)).await;
            }
        }
        KeyCode::Esc => {
            // 退出提交列表视图，返回分支列表
            app_state
                .update_app(|app| {
                    app.ui_state = crate::ui::app::AppState::BranchList;
                    app.selected_index = 0; // 重置选择索引，从第一个分支开始
                    app.set_notification("Returned to branch list".to_string(), 1500);
                })
                .await;
        }
        // 可以添加其他功能，比如按Enter查看提交详情
        _ => {}
    }

    Ok(())
}

pub async fn handle_notifications(tx: mpsc::Sender<AppEvent>, app_state: AppState) {
    // 每100ms检查一次通知是否过期
    let mut interval = time::interval(Duration::from_millis(100));

    loop {
        interval.tick().await;

        let notification_changed = app_state
            .update_app(|app| {
                let had_notification = app.notification.is_some();
                app.check_notification();
                // 如果通知状态改变（从有到无），返回true
                had_notification && app.notification.is_none()
            })
            .await;

        // 只有当通知状态改变时才重新渲染
        if notification_changed {
            let _ = tx.send(AppEvent::Render).await;
        }
    }
}

// 处理用户输入的异步任务
pub async fn handle_input(tx: mpsc::Sender<AppEvent>) {
    let input_check_interval = Duration::from_millis(50);

    loop {
        // 使用 poll 检查是否有输入事件
        if let Ok(true) = crossterm::event::poll(input_check_interval) {
            if let Ok(Event::Key(key)) = event::read() {
                if key.kind == KeyEventKind::Release {
                    continue; // 忽略按键释放事件
                }
                // 处理全局退出键
                if key.code == KeyCode::Char('q') {
                    let _ = tx.send(AppEvent::Quit).await;
                    break;
                } else {
                    // 发送其他按键事件
                    let _ = tx.send(AppEvent::KeyPress(key)).await;
                }
            }
        }
    }
}

// 处理Git操作结果
pub async fn process_git_result(
    app_state: &AppState,
    operation: &str,
    result: GitResult,
) -> Result<()> {
    match result {
        GitResult::Branches(branches) => {
            app_state
                .update_app(|app| {
                    app.branches = branches;
                })
                .await;
        }
        GitResult::Commits(commits) => {
            app_state
                .update_app(|app| {
                    app.commits = commits;
                })
                .await;
        }
        GitResult::RepoStatus(status) => {
            // 更新仓库状态
            let has_changes = !status.modified.is_empty()
                || !status.untracked.is_empty()
                || !status.staged.is_empty()
                || !status.conflicted.is_empty();

            app_state
                .update_app(|app| {
                    app.set_has_changes(has_changes);
                })
                .await;
        }
        GitResult::CurrentBranch(branch) => {
            // 更新当前分支信息
            app_state
                .update_app(|app| {
                    app.set_current_branch(branch);
                })
                .await;
        }
        GitResult::Success => {
            // 如果是成功的操作，可能需要更新状态
            if operation.starts_with("checkout_branch:") {
                // 切换分支后再次获取仓库状态和当前分支
                app_state.git_manager.get_repo_status().await?;

                // 获取当前分支名
                if let Ok(branch) = crate::git::commands::get_current_branch().await {
                    app_state
                        .update_app(|app| {
                            app.set_current_branch(branch);
                        })
                        .await;
                }
            }
        }
        GitResult::MergeSuccess => {
            // 合并成功后，更新仓库状态
            app_state.git_manager.get_repo_status().await?;

            app_state
                .update_app(|app| {
                    app.set_notification("Merge completed successfully".to_string(), 3000);
                })
                .await;
        }
        GitResult::MergeConflict { conflicts } => {
            // 合并冲突，显示通知
            app_state
                .update_app(|app| {
                    app.set_notification(
                        format!(
                            "Merge conflicts detected in {} files. Please resolve manually.",
                            conflicts.len()
                        ),
                        5000,
                    );
                })
                .await;
        }
    }

    Ok(())
}

pub async fn handle_dialog_key(app_state: &AppState, key: KeyCode) -> Result<()> {
    match key {
        KeyCode::Up | KeyCode::Char('k') => {
            app_state
                .update_app(|app| {
                    app.prev_dialog_option();
                })
                .await;
        }
        KeyCode::Down | KeyCode::Char('j') => {
            app_state
                .update_app(|app| {
                    app.next_dialog_option();
                })
                .await;
        }
        KeyCode::Enter => {
            // 获取选择的选项
            let selected_option = app_state
                .update_app(|app| {
                    let option = app.get_selected_dialog_option();
                    app.close_dialog(); // 关闭对话框
                    option
                })
                .await;

            // 如果有选择的选项，发送选项选择事件
            if let Some(option) = selected_option {
                // 从选项值中解析对话框 ID 和分支名称
                // 格式: "action:branch_name"
                let parts: Vec<&str> = option.value.split(':').collect();
                if parts.len() >= 2 {
                    let action = parts[0];
                    let branch = parts[1..].join(":");

                    match action {
                        "checkout" => {
                            // 调用 GitManager 的方法来切换分支
                            let checkout_op = app_state.git_manager.checkout_branch(&branch, false);
                            checkout_op.wait().await?;
                            app_state
                                .update_app(|app| {
                                    app.set_current_branch(branch.clone());
                                    app.set_notification(
                                        format!("Switched to branch '{}'", branch),
                                        3000,
                                    );
                                })
                                .await;
                        }
                        "checkout_force" => {
                            // 调用 GitManager 的方法来切换分支，使用 force 参数
                            let checkout_op = app_state.git_manager.checkout_branch(&branch, true);
                            checkout_op.wait().await?;
                            app_state
                                .update_app(|app| {
                                    app.set_current_branch(branch.clone());
                                    app.set_notification(
                                        format!("Force switched to branch '{}'", branch),
                                        3000,
                                    );
                                })
                                .await;
                        }
                        "stash_checkout" => {
                            // 先 stash 修改，再切换分支
                            // 这里需要实现 stash 操作，这需要在 GitManager 中添加
                            // TODO: 实现 stash 功能

                            // 然后切换分支
                            let checkout_op = app_state.git_manager.checkout_branch(&branch, false);
                            checkout_op.wait().await?;
                            app_state
                                .update_app(|app| {
                                    app.set_current_branch(branch.clone());
                                    app.set_notification(
                                        format!(
                                            "Stashed changes and switched to branch '{}'",
                                            branch
                                        ),
                                        3000,
                                    );
                                })
                                .await;
                        }
                        _ => {
                            // 未知操作，不做任何事
                        }
                    }
                }
            }
        }
        KeyCode::Esc => {
            // 关闭对话框
            app_state
                .update_app(|app| {
                    app.close_dialog();
                })
                .await;
        }
        _ => {}
    }

    Ok(())
}
